#include <myhead.h>
#include <sqlite3.h>
#include "dao.h"

extern sqlite3* db;

int tbl_user_insert(char* username, char* passwd){
	//printf("in tbl_user_insert! username=[%s], passwd=[%s]\n", username, passwd);
	char sql[]="insert into tbl_user (username,passwd)values(?,?);";

	sqlite3_stmt *pStmt;
	if(sqlite3_prepare_v2(db,sql,sizeof(sql), &pStmt, NULL)!=SQLITE_OK){
		fprintf(stderr, "sqlite3_prepare error\n");
		return -1;
	}
	
	sqlite3_bind_text(pStmt,1, username, strlen(username), NULL);
	sqlite3_bind_text(pStmt,2, passwd, strlen(passwd), NULL);

	int retStep=sqlite3_step(pStmt);
	//printf("tbl_user_insert. retStep=[%d]\n", retStep);

	sqlite3_finalize(pStmt);

	return 0;
}

int tbl_user_select(char* username, db_user_t* data){
	char sql[]="select username,passwd from tbl_user where username=?;";
	
	sqlite3_stmt *pStmt;
	if(sqlite3_prepare_v2(db,sql,sizeof(sql), &pStmt, NULL)!=SQLITE_OK){
		fprintf(stderr, "sqlite3_prepare error\n");
		perror("sqlite3_prepare error");
		return -1;
	}
	
	sqlite3_bind_text(pStmt,1,username, strlen(username), NULL);

	int stepRet=sqlite3_step(pStmt);
	//printf("stepRet=[%d],SQLITE_ROW=[%d],SQLITE_DONE=[%d]\n", stepRet, SQLITE_ROW, SQLITE_DONE);
	if(stepRet==SQLITE_ROW){
		strcpy(data->username, sqlite3_column_text(pStmt, 0));
		strcpy(data->passwd, sqlite3_column_text(pStmt, 1));
		printf("tbl_user_select查询到了数据:username=[%s], passwd=[%s]\n", data->username, data->passwd);

		sqlite3_finalize(pStmt);
		return 1;
	}
	if(stepRet==SQLITE_DONE){//成功执行了sql但是，没有查询到数据
		sqlite3_finalize(pStmt);
		return 0;
	}
	sqlite3_finalize(pStmt);

	return -1;
}

